import os
import sys
import time
import datetime
import warnings

import pandas as pd
from dateutil.tz import *

sys.path.append('..')
warnings.filterwarnings('ignore')

from tools.setting import DATA_DIR
from API.binance import fetch_binance_perpetual_leverage_margin, fetch_binance_margin_interest_rate
from API.okex import get_margin_interest_rate_okex
from API.loanscan import get_lend_borrow_fee_rate
from API.aave import get_aave_borrow_amount, get_aave_borrow_fee_rate
from tools.logger import logger

EXCHANGE_INFO_DATA_DIR = os.path.join(DATA_DIR, 'exchange_information')
os.makedirs(EXCHANGE_INFO_DATA_DIR, exist_ok=True)
INTEREST_DATA_DIR = os.path.join(EXCHANGE_INFO_DATA_DIR, 'margin_interest_rate')
os.makedirs(INTEREST_DATA_DIR, exist_ok=True)


def update_perpetual_leverage_and_margin_binance():
    # 更新币安永续合约杠杆和保证金比例
    logger.info('更新币安永续合约杠杆和保证金比例')
    file_name = os.path.join(EXCHANGE_INFO_DATA_DIR, f'leverage_and_margin_binance.csv')
    df = fetch_binance_perpetual_leverage_margin()
    if os.path.exists(file_name):
        historical_data = pd.read_csv(file_name)
        df = pd.concat([historical_data, df], axis=0, ignore_index=True)
        df.drop_duplicates(subset=['bracketSeq', 'symbol', 'updateTime'], inplace=True)
    df.to_csv(file_name)


def update_margin_interest_rate_binance():
    # 更新币安借贷利率
    logger.info('更新币安借贷利率')
    file_name = os.path.join(INTEREST_DATA_DIR, f'binance_margin_interest_rate.csv')
    if os.path.exists(file_name):
        historical_data = pd.read_csv(file_name, index_col='end_date')
        latest_date = historical_data.index[-1]
        start = time.mktime(
            datetime.datetime(int(latest_date[:4]), int(latest_date[5:7]), int(latest_date[-2:]), 0, 0, 0,
                              tzinfo=tzutc()).timetuple())
    else:
        start = time.mktime(datetime.datetime(2018, 1, 1, 0, 0, 0, tzinfo=tzutc()).timetuple())
        historical_data = pd.DataFrame()
    end_date = (datetime.datetime.today() - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
    end = time.mktime(datetime.datetime(int(end_date[:4]), int(end_date[5:7]), int(end_date[-2:]), 23, 59, 59,
                                        tzinfo=tzutc()).timetuple())
    df_list = []
    for asset in ['USDT', 'BUSD', 'BTC', 'ETH']:
        logger.info(f'开始从binance获取{asset}的借贷费率')
        df = fetch_binance_margin_interest_rate(asset=asset, start_time=start,  end_time=end)
        df['start_time'] = df.apply(lambda x: int(x['timestamp'] / 1000), axis=1)
        df['end_date'] = pd.to_datetime(df['start_time'], unit='s').dt.tz_localize('UTC').dt.tz_convert('+0000')
        df['end_date'] = df['end_date'].dt.strftime('%Y-%m-%d')
        df['datetime'] = pd.to_datetime(df['start_time'], unit='s').dt.tz_localize('UTC').dt.tz_convert('+0000')
        df['datetime'] = df['datetime'].dt.strftime('%Y-%m-%d %H:%M:%S')
        df = df[~df.duplicated(subset='end_date')]
        df.set_index('end_date', inplace=True)
        df.rename(columns={'margin_interest_rate': f'{asset}_margin_interest_rate'}, inplace=True)
        df_list.append(df[f'{asset}_margin_interest_rate'])
    df = pd.concat(df_list, axis=1)
    if os.path.exists(file_name):
        df = pd.concat([historical_data, df], axis=0)
        df = df[~df.index.duplicated(keep='last')]
    df.to_csv(file_name)


def update_margin_interest_rate_okex():
    # 更新okex借贷利率
    logger.info('更新okex借贷利率')
    df = get_margin_interest_rate_okex()
    file_name = os.path.join(INTEREST_DATA_DIR, f'okx_margin_interest_rate.csv')
    df.to_csv(file_name, index=False)


def update_margin_interest_rate_loanscan():
    # 从loanscan更新选定协议借贷利率
    logger.info('更新选定协议借贷利率')
    for protocol in ['aave', 'compound', 'dydx', 'makerdao']:
        df_list = []
        for lend_or_borrow in ['lend', 'borrow']:
            for asset in ['USDC', 'DAI', 'ETH', 'WBTC']:
                df = get_lend_borrow_fee_rate(protocol=protocol, lend_or_borrow=lend_or_borrow, asset=asset)
                if df is not None:
                    df.rename(columns={f'{lend_or_borrow}_rate': f'{protocol}_{asset}_{lend_or_borrow}_rate'},
                              inplace=True)
                    df_list.append(df)
        all_df = pd.concat(df_list, axis=1)
        file_name = os.path.join(INTEREST_DATA_DIR, f'loanscan_{protocol}_margin_interest_rate.csv')
        all_df.to_csv(file_name)


def update_margin_interest_rate_aave():
    # 更新aave借贷利率
    logger.info('更新aave借贷利率')
    for asset in ['USDC', 'DAI', 'ETH', 'WBTC']:
        df = get_aave_borrow_fee_rate(asset=asset)
        df = df.groupby(['date'])[df.columns[:4]].mean()
        file_name = os.path.join(INTEREST_DATA_DIR, f'aave_{asset}_margin_interest_rate.csv')
        df.to_csv(file_name)
        time.sleep(5)

    df = get_aave_borrow_amount()
    file_name = os.path.join(INTEREST_DATA_DIR, f'aave_margin_tvl_borrowed.csv')
    df.to_csv(file_name)


if __name__ == '__main__':
    # update_perpetual_leverage_and_margin_binance()
    # update_margin_interest_rate_binance()
    # update_margin_interest_rate_okex()
    # update_margin_interest_rate_aave()
    # 定时任务并没有运行
    update_margin_interest_rate_loanscan()

